import os
from waitress import serve

from app.AppBlueprint import app
from config.Config import Config
from Libs.logs.logs import logger


class TornadoServer:
    def __init__(self):
        if not hasattr(Config, "SERVER_PORT"):
            logger.info(" * 无默认端口，自动默认9998！")
            Config.SERVER_PORT = 9998
        if not hasattr(Config, "DEBUG"):
            logger.info(" * 无默认调试模式，自动默认False！")
            Config.DEBUG = "False"
        self.port = Config.SERVER_PORT
        self.debug = Config.DEBUG

    def run(self) -> None:
        self.write_pid()
        if self.debug == "True":
            logger.info('当前配置文件为测试配置，请注意数据库！')
            logger.info(f"以调试模式开启监听服务器，可以访问验证：http://127.0.0.1:{self.port}/{Config.PROJECT_NAME}")
            app.run(port=self.port, debug=True)
        else:
            logger.info(f"http://127.0.0.1:{self.port}/data_aggregation/static/index.html")
            logger.info(f"super_login: http://127.0.0.1:{self.port}/{Config.PROJECT_NAME}/super_login?username=admin&password=admin123&secret_key=fskj_super_admin_2024")
            serve(
                app,
                host="0.0.0.0",
                port=self.port,
                threads=8,
                channel_timeout=120
            )

    @staticmethod
    def write_pid():
        with open("pid.pid", "w") as f:
            f.write(f"{os.getpid()}")


if __name__ == '__main__':
    TornadoServer().run()